package com.xiliubit.cloudpicture.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiliubit.cloudpicture.annotation.AuthCheck;
import com.xiliubit.cloudpicture.common.BaseResponse;
import com.xiliubit.cloudpicture.common.DeleteRequest;
import com.xiliubit.cloudpicture.common.ResultUtils;
import com.xiliubit.cloudpicture.constant.UserConstant;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.manager.PictureDeleteManager;
import com.xiliubit.cloudpicture.manager.auth.SpaceUserAuthManager;
import com.xiliubit.cloudpicture.model.dto.space.SpaceAddRequest;
import com.xiliubit.cloudpicture.model.dto.space.SpaceEditRequest;
import com.xiliubit.cloudpicture.model.dto.space.SpaceQueryRequest;
import com.xiliubit.cloudpicture.model.dto.space.SpaceUpdateRequest;
import com.xiliubit.cloudpicture.model.entity.Picture;
import com.xiliubit.cloudpicture.model.entity.Space;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.SpaceLevelEnum;
import com.xiliubit.cloudpicture.model.vo.SpaceLevel;
import com.xiliubit.cloudpicture.model.vo.SpaceVO;
import com.xiliubit.cloudpicture.service.PictureService;
import com.xiliubit.cloudpicture.service.SpaceService;
import com.xiliubit.cloudpicture.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Tag(name = "空间接口")
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private PictureService pictureService;

    @Resource
    private PictureDeleteManager pictureDeleteManager;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 添加空间
     *
     * @param spaceAddRequest 添加的空间数据
     * @param request         请求
     * @return 添加的空间id
     */
    @PostMapping("/add")
    @Operation(summary = "添加空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        log.info("添加空间:{}", spaceAddRequest);
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        ThrowUtils.throwIf(spaceId <= 0, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(spaceId);
    }

    /**
     * 获取空间信息（仅管理员）
     *
     * @param id 空间id
     * @return 空间信息
     */
    @GetMapping("/get")
    @Operation(summary = "根据id获取空间（管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(Long id) {
        log.info("获取空间信息：{}", id);
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间VO
     *
     * @param id id
     * @return 脱敏后的空间信息
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据id获取空间VO")
//    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        log.info("根据 id 获取空间VO:{}", id);
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页查询空间（管理员）
     *
     * @param pictureQueryRequest 空间查询参数
     * @param request             请求
     * @return 空间分页列表
     */
    @PostMapping("/list/page")
    @Operation(summary = "获取空间列表(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest pictureQueryRequest,
                                                     HttpServletRequest request) {
        log.info("获取空间列表(管理员):{}", pictureQueryRequest);
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(pictureQueryRequest);
        // 查询数据库
        Page<Space> picturePage = spaceService.page(new Page<>(pictureQueryRequest.getCurrent(),
                pictureQueryRequest.getPageSize()), queryWrapper);
        return ResultUtils.success(picturePage);
    }
    /**
     * 分页查询空间（管理员）
     *
     * @param pictureQueryRequest 空间查询参数
     * @param request             请求
     * @return 空间分页列表
     */
    @PostMapping("/list/page/vo")
    @Operation(summary = "获取空间列表")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest pictureQueryRequest,
                                                     HttpServletRequest request) {
        log.info("获取空间列表:{}", pictureQueryRequest);
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(pictureQueryRequest);
        // 查询数据库
        Page<Space> picturePage = spaceService.page(new Page<>(pictureQueryRequest.getCurrent(),
                pictureQueryRequest.getPageSize()), queryWrapper);
        Page<SpaceVO> pictureVOPage = spaceService.getSpaceVOPage(picturePage, request);
        return ResultUtils.success(pictureVOPage);
    }
    /**
     * 修改空间
     *
     * @param spaceEditRequest 修改的空间数据
     */
    @PostMapping("/edit")
    @Operation(summary = "修改空间")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest,
                                           HttpServletRequest request) {
        log.info("修改空间:{}", spaceEditRequest);
        if (spaceEditRequest == null || spaceEditRequest.getId() == null || spaceEditRequest.getId() <= 0 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = spaceEditRequest.getId();
        String spaceName = spaceEditRequest.getSpaceName();
        // 校验参数
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可更改
        User loginUser = userService.getLoginUser(request);
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 封装数据
        space.setSpaceName(spaceName);
        spaceService.validSpace(space, false);
        // 更新
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    @Operation(summary = "更新空间(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        log.info("更新空间:{}", spaceUpdateRequest);
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @GetMapping("/list/level")
    @Operation(summary = "获取空间等级")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        log.info("获取空间等级");
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

    /**
     * 删除空间
     *
     * @param deleteRequest 包含空间id
     */
    @PostMapping("/delete")
    @Operation(summary = "删除空间")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        log.info("删除空间:{}", deleteRequest);
        ThrowUtils.throwIf(deleteRequest == null
                || deleteRequest.getId() == null
                || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        // 判断空间是否存在
        Space oldSpace = spaceService.getById(deleteRequest.getId());
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        Long spaceId = deleteRequest.getId();
        // 仅本人或管理员可删除
        if (!oldSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        List<Picture> thePictureList = transactionTemplate.execute(status -> {
            // 获取删除的空间内的所有照片的url
            QueryWrapper<Picture> pictureQueryWrapper = new QueryWrapper<>();
            pictureQueryWrapper.eq("spaceId", spaceId);
            pictureQueryWrapper.eq("isDelete", 0);
            List<Picture> pictureList = pictureService.list(pictureQueryWrapper);

            // 操作数据库
            boolean result = spaceService.removeById(spaceId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 使用lambda方式删除这个空间id的图片表里的数据
            pictureService.lambdaUpdate()
                    .eq(Picture::getSpaceId, spaceId)
                    .set(Picture::getIsDelete, 1) // 改为逻辑删除
                    .update();
            // 获取删除的空间内的所有照片的url
            return pictureList;
        });
        // 删除cos图片文件
//        pictureService.clearPictureFile(thePictureList);
        pictureDeleteManager.deletePictureList(thePictureList);
        return ResultUtils.success(true);
    }
}
